package com.panda.web.controller.aims;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import com.panda.common.core.domain.R;
import com.panda.web.domain.vo.aims.AimsVO;
import com.panda.web.entity.aims.*;
import com.panda.web.entity.commons.WechatResume;
import com.panda.web.entity.wechatinfo.UserDemand;
import com.panda.web.entity.wechatinfo.UserMajorRgpp;
import com.panda.web.entity.wechatinfo.UserProject;
import com.panda.web.entity.wechatinfo.WechatUserinfo;
import com.panda.web.mapper.aims.CallAiMapper;
import com.panda.web.mapper.aims.CallRecordsMapper;
import com.panda.web.mapper.aims.QuestionBankMapper;
import com.panda.web.mapper.commons.WechatResumeMapper;
import com.panda.web.mapper.wechatinfo.UserDemandMapper;
import com.panda.web.mapper.wechatinfo.UserMajorRgppMapper;
import com.panda.web.mapper.wechatinfo.UserProjectMapper;
import com.panda.web.mapper.wechatinfo.WechatUserinfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/ai-call")
public class AICallController {
    @Autowired
    private QuestionBankMapper questionBankMapper;//通用题库
    @Autowired
    private WechatUserinfoMapper userinfoMapper;

    @Autowired
    private App rtcTokenService;

    @Autowired
    private UserMajorRgppMapper majorRgppMapper;
    @Autowired
    private WechatResumeMapper resumeMapper;
    @Autowired
    private CallRecordsMapper callRecordsMapper;//通话记录实例
    @Autowired
    private CallAiMapper callAiMapper;
    @Autowired
    private UserProjectMapper userProjectMapper;//实习经历
    @Autowired
    private UserDemandMapper userDemandMapper;
    @Value("${aliyun.ai}")
    private String aimsUrl;
    private static Font titleFont;
    private static Font agentFont;
    private static Font userFont;
    private static final String BACKGROUND_PATH = "/www/wwwroot/comments/picture/50.png"; // 背景图片路径

    //    private static final String BACKGROUND_PATH = "C:/Users/Administrator/Desktop/AI面试/jilu/50.png"; // 背景图片路径
    static {
        try {
            // 使用更可靠的中文字体加载方式
//            String fontPath = "C:/Users/Administrator/Desktop/AI面试/jilu/msyh.ttf"; // 使用系统自带的黑体
            String fontPath = "/www/wwwroot/comments/Fonts/msyh.ttf"; // 使用系统自带的黑体
            BaseFont bfChinese = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            titleFont = new Font(bfChinese, 16, Font.BOLD);
            agentFont = new Font(bfChinese, 12, Font.BOLD, new BaseColor(25, 91, 169));
            userFont = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLACK);
        } catch (Exception e) {
            // 回退到默认字体
            titleFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
            agentFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD, new BaseColor(25, 91, 169));
            userFont = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL, BaseColor.BLACK);
            e.printStackTrace();
        }
    }

    /**
     * 是否可以面试
     * @param openid
     * @return
     */
    @GetMapping("/whether/interview")
    public R getUserAims( @RequestParam("openid") String openid){
        //根据openid 查询是否填写岗位、实习经历
        WechatUserinfo userinfo = userinfoMapper.findByOpenid(openid);
        if (userinfo==null){
            throw new RuntimeException("人岗匹配未填写");
        }
        // 检查实习经历
        List<UserProject> userProjectList = userProjectMapper.findByOpenid(openid);
        if (userProjectList == null || userProjectList.isEmpty()) {
            throw new RuntimeException("未填写实习经历，请先填写实习经历，进行面试");
        }

// 检查岗位信息
        List<UserMajorRgpp> userMajorRgppList = majorRgppMapper.findByOpenid(openid);
        if (userMajorRgppList == null || userMajorRgppList.isEmpty()) {
            throw new RuntimeException("未填写岗位信息，请先填写岗位信息，进行面试");
        }
        return R.ok(1,200,"ok");
    }

    @Async
    @PostMapping("/agent")
    public synchronized ResponseEntity<String> handleAgentCallback(
            @RequestBody AgentCallbackRequest callbackRequest) throws JsonProcessingException {

        // 1. 打印原始回调信息（JSON格式化）
        log.info("\n============== 收到原始回调 ==============\n" +
                        "Agent ID: {}\n" +
                        "Instance ID: {}\n" +
                        "Event Type: {}\n" +
                        "Timestamp: {}\n" +
                        "Full Data:\n{}\n" +
                        "========================================",
                callbackRequest.getAiAgentId(),
                callbackRequest.getInstanceId(),
                callbackRequest.getEvent(),
                callbackRequest.getTimestamp(),
                new Gson().toJson(callbackRequest));

            // 2. 直接转换对象（推荐方案）
            AgentCallbackRequestVO vo = convertToVO(callbackRequest);
            // 3. 验证转换结果

            log.info("转换后的VO对象: {}", new Gson().toJson(vo));
            if (vo.getData() != null) {
                CallRecords records = new CallRecords();
                records.setInstanceId(vo.getInstanceId());
                records.setCode(vo.getCode());
                records.setEvent(vo.getEvent());
                records.setRole(vo.getData().getRole().get_value());
                String text = removeMarkdown(vo.getData().getText().get_value());
                records.setText(text);
                // 从 userData Map 中提取 openid
                if (vo.getUserData() != null) {
                    Object idValue = vo.getUserData().get("id");
                    if (idValue != null) {
                        records.setOpenid(idValue.toString());
                    } else {
                        log.warn("userData 中未找到 id 字段: {}", vo.getUserData());
                    }
                }

                Date date = new Date();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = format.format(date);
                records.setCreateTime(date);
                records.setCreationTime(time);
                callRecordsMapper.insert(records);
            }


        try {
            // 2. 根据事件类型处理
            switch (callbackRequest.getEvent()) {
                case "agent_start":
                    printAgentStart(callbackRequest);
                    break;
                case "session_start":
                    printSessionStart(callbackRequest);
                    break;
                case "chat_record":
                    printChatRecord(callbackRequest);
                    break;
                case "agent_stop":
                    printAgentStop(callbackRequest);
                    break;
                case "llm_data_received":
                    printLlmData(callbackRequest);
                    break;
                default:
                    log.warn("未知事件类型: {}", callbackRequest.getEvent());
            }

            return ResponseEntity.ok("Callback processed (debug mode)");
        } catch (Exception e) {
            log.error("处理回调时出错: ", e);
            return ResponseEntity.internalServerError().body("Error processing callback");
        }
    }

    private String removeMarkdown(String text) {
        if (text == null) {
            return null;
        }

        // 去除Markdown加粗标记
        text = text.replaceAll("\\*\\*", "");
        // 去除Markdown标题标记
        text = text.replaceAll("^#+\\s*", "");
        // 去除行内的Markdown标题标记（前面有空格的情况）
        text = text.replaceAll("\\s#+\\s*", " ");

        return text.trim();
    }

    //转化出来对象
    private AgentCallbackRequestVO convertToVO(AgentCallbackRequest request) throws JsonProcessingException {
        AgentCallbackRequestVO vo = new AgentCallbackRequestVO();
        // 复制基本字段
        vo.setAiAgentId(request.getAiAgentId());
        vo.setInstanceId(request.getInstanceId());
        vo.setEvent(request.getEvent());
        vo.setCode(request.getCode());
        vo.setMessage(request.getMessage());

        // 1. 解析userData，获取其中的第一个值
        ObjectMapper objectMapper = new ObjectMapper();

        // 2. 转换timestamp格式
        DateTimeFormatter inputFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(request.getTimestamp(), inputFormatter);
        vo.setTimestamp(dateTime.format(outputFormatter));

        // 解析userData - 修复：userData现在是JSON字符串，需要先解析为Map
        if (request.getUserData() != null && !request.getUserData().isEmpty()) {
            try {
                // userData是JSON字符串，直接解析为Map
                Map<String, Object> userDataMap = objectMapper.readValue(request.getUserData(), Map.class);
                vo.setUserData(userDataMap);
            } catch (Exception e) {
                log.warn("解析userData失败: {}", request.getUserData(), e);
                vo.setUserData(new HashMap<>());
            }
        }


        // 处理data字段（根据实际接收到的简化结构）
        if (request.getData() != null && !request.getData().isNull()) {
            JsonNode dataNode = request.getData();
            ChatRecordData chatRecordData = new ChatRecordData();


            // 直接解析简化后的字段
            if (dataNode.has("role")) {
                ChatRecordData.ValueRoleA children = new ChatRecordData.ValueRoleA();
                children.set_value(dataNode.get("role").asText());
                chatRecordData.setRole(children);
            }

            if (dataNode.has("type")) {
                ChatRecordData.ValueTypeA type = new ChatRecordData.ValueTypeA();
                type.set_value(dataNode.get("type").asText());
                chatRecordData.setType(type);
            }

            if (dataNode.has("text")) {
                ChatRecordData.ValueTextA text = new ChatRecordData.ValueTextA();
                text.set_value(dataNode.get("text").asText());
                chatRecordData.setText(text);
            }

            if (dataNode.has("sentence_id")) {
                ChatRecordData.ValueSenA sentenceId = new ChatRecordData.ValueSenA();
                sentenceId.set_value(String.valueOf(dataNode.get("sentence_id").asInt()));
                chatRecordData.setSentence_id(sentenceId);
            }

            vo.setData(chatRecordData);
        }

        return vo;
    }


    // === 各事件处理方法 ===
    private void printAgentStart(AgentCallbackRequest request) {
        log.info("\n🎬 智能体启动事件\n" +
                        "|-- Agent ID: {}\n" +
                        "|-- 启动时间: {}\n" +
                        "|-- 状态码: {}\n" +
                        "|-- 消息: {}",
                request.getAiAgentId(),
                request.getTimestamp(),
                request.getCode(),
                request.getMessage());
    }

    private void printSessionStart(AgentCallbackRequest request) {
        log.info("\n通话建立事件\n" +
                        "|-- Instance ID: {}\n" +
                        "|-- 用户ID: {}\n" +
                        "|-- 频道ID: {}\n" +
                        "|-- 开始时间: {}",
                request.getInstanceId(),
                extractUserIdFromString(request.getUserData()),
                request.getChannelId(),
                request.getTimestamp());
    }

    private void printChatRecord(AgentCallbackRequest request) {
        try {
            log.info("开始打印聊天记录...");


        } catch (Exception e) {
            log.error("解析chat_record失败", e);
        }
    }

    private void printAgentStop(AgentCallbackRequest request) {

        if (Objects.equals(request.getCode(), "1002")) {
            List<CallRecords> callRecords = callRecordsMapper.findByInstanceId(request.getInstanceId());
            if (callRecords.size() > 3) {
                //对话记录大于5生成报告
                String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                try {
                    // 生成PDF报告
                    String outputPath = aimsUrl + time + "/" + request.getInstanceId() + ".pdf";
                    generateSimplePdf(callRecords, outputPath);
                    System.out.println("PDF报告生成成功: " + outputPath);
                } catch (Exception e) {
                    System.err.println("生成PDF报告失败: " + e.getMessage());
                    e.printStackTrace();
                }

                //生成pdf 通话记录
                CallAi callAi = new CallAi();
                if (request.getInstanceId() != null) {
                    callAi.setInstanceId(request.getInstanceId());
                }
                callAi.setName(new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "AI面试报告");
                callAi.setOpenid(callRecords.get(0).getOpenid());
                callAi.setUrl("https://houtaiguanli.yanbeibao2021.com/file/aims/" + time + "/" + request.getInstanceId() + ".pdf");
                callAi.setCreationTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                callAiMapper.insert(callAi);

            } else {
                log.info("通话记录小于三条,无法记录");
            }

        } else {
            log.info("\n通话结束事件\n" +
                            "|-- Instance ID: {}\n" +
                            "|-- 结束原因: {}\n" +
                            "|-- 结束时间: {}\n" +
                            "|-- 状态码: {}",
                    request.getInstanceId(),
                    request.getMessage(),
                    request.getTimestamp(),
                    request.getCode());

        }

    }

    private void printLlmData(AgentCallbackRequest request) {
//        log.info("\nLLM响应数据\n" +
//                        "|-- 请求时间: {}\n" +
//                        "|-- 响应时间: {}\n" +
//                        "|-- 处理耗时: {}ms",
//                request.getRequestTimestamp(),
//                request.getResponseTimestamp(),
//                calculateTimeDiff(request.getRequestTimestamp(), request.getResponseTimestamp()));
    }

    // === 辅助方法 ===
    private String extractUserId(Map<String, Object> userData) {
        try {
            if (userData != null && !userData.isEmpty()) {
                Object idValue = userData.get("id");
                if (idValue != null) {
                    return idValue.toString();
                }
            }
        } catch (Exception e) {
            log.warn("解析userData失败: {}", userData);
        }
        return "未知";
    }

    private String extractUserIdFromString(String userDataString) {
        try {
            if (userDataString != null && !userDataString.isEmpty()) {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> userDataMap = objectMapper.readValue(userDataString, Map.class);
                return extractUserId(userDataMap);
            }
        } catch (Exception e) {
            log.warn("解析userData字符串失败: {}", userDataString, e);
        }
        return "未知";
    }

    private long calculateTimeDiff(String start, String end) {
        try {
            Instant startTime = Instant.parse(start);
            Instant endTime = Instant.parse(end);
            return Duration.between(startTime, endTime).toMillis();
        } catch (Exception e) {
            return -1;
        }
    }


    @GetMapping("/config")
    public ResponseEntity<Map<String, Object>> getCallConfig(@RequestParam("openid") String openid) {
//        String channelId = "ai_call_" + UUID.randomUUID().toString().replace("-", "");

        String appid = "7804e660-8031-4c77-bd19-71483256d6bf";
        String appkey = "7ac1a312ae613b60d58aee237490cf20";
        String channel_id = com.panda.common.utils.uuid.UUID.randomUUID().toString();
        String user_id = openid;

        String base64token = rtcTokenService.createBase64Token(appid, appkey, channel_id, user_id);

        Map<String, Object> config = new HashMap<>();
        config.put("agentId", "89101202d3e543f28b4f1dbda7de2c06"); //智能体id
        config.put("region", "cn-hangzhou");
        config.put("rtcToken", base64token);

        return ResponseEntity.ok(config);
    }

    private static final Map<String, String> AGENT_MAPPING = new HashMap<>() {{
        put("voice", "agt_voice_123");      // 纯语音智能体ID
        put("avatar", "agt_avatar_456");    // 数字人智能体ID
        put("vision", "agt_vision_789");    // 视觉理解智能体ID
    }};

    private String getAgentIdByType(String type) {
        // 实现根据类型获取对应agentId的逻辑
        return AGENT_MAPPING.getOrDefault(type.toLowerCase(), "default_agent_id");
    }

    /**
     * 动态内容
     */
    @Transactional
    @GetMapping("/contents")
    public R getContent(@RequestParam("openid") String openid,@RequestParam(value = "type", required = false)  String type) throws IOException {
        String appid = "c036f7e6-6cc4-425d-9754-10b424dbd0b9";//智能体RTC AppID
        String appkey = "7ba43b6a40005af3346e057c604d67fe";  //视觉
        String channel_id = com.panda.common.utils.uuid.UUID.randomUUID().toString();
        String user_id = openid;
        log.info("channel_id:{}", channel_id);


        String base64token = rtcTokenService.createBase64Token(appid, appkey, channel_id, user_id);
        AimsVO vo = new AimsVO();
        vo.setRegion("cn-hangzhou");//地区
        vo.setAgentId("b81b02ac970645dbb0c92ea096c20f57");//智能体id
        vo.setRtcToken(base64token);
        //根据openid 查询岗位
        String post = null;
        List<UserDemand> demandList = userDemandMapper.findByOpenid(openid);
        if (demandList!=null&&!demandList.isEmpty()){
            for (UserDemand userDemand : demandList) {
                if (userDemand.getJobIntention()!=null){
                    if (userDemand.getSearchCompany()!=null){
                        post = userDemand.getSearchCompany()+"的"+userDemand.getJobIntention()+"的岗位";
                    }else {
                        post = userDemand.getJobIntention();
                    }
                }else {
                    throw new RemoteException("请完善，求职需求，在进行面试");
                }

            }
        } else {
            throw new RuntimeException("请先填写求职需求，在进行面试");
        }
//        List<UserMajorRgpp> userMajorRgppList = majorRgppMapper.findByOpenid(openid);
//        if (userMajorRgppList != null && !userMajorRgppList.isEmpty()) {
//            for (UserMajorRgpp userMajorRgpp : userMajorRgppList) {
//                post = userMajorRgpp.getMajorName() + ";";
//            }
//        }

        String resumeContent = null; //简历内容
        List<UserProject> userProjectList = userProjectMapper.findByOpenid(openid);
        if (userProjectList != null && !userProjectList.isEmpty()) {
            resumeContent = "实习公司：" + userProjectList.get(0).getName() + ",所属部门：" + userProjectList.get(0).getDept() + ",职位：" + userProjectList.get(0).getPost() + ",工作内容：" + userProjectList.get(0).getContent();
        } else {
            throw new RemoteException("请先在个人中心填写实习经历");
        }
        //获取简历内容
//        List<WechatResume> wechatResumeList = resumeMapper.findByOpenid(openid);
//        if (wechatResumeList != null && !wechatResumeList.isEmpty()) {
//            String image = wechatResumeList.get(0).getUrl();
//            String updatedImage = image.replace("https://houtaiguanli.yanbeibao2021.com", "/www/wwwroot/houtaiguanli.yanbeibao2021.com/dist");
//            resumeContent = convertPdfToText(updatedImage);
////            resumeContent = convertPdfToText("C:/Users/Administrator/Desktop/AI面试/905db149-dbea-45b7-a0d8-5a46f024e5a0.pdf");//本地测试文件
//        } else {
//            System.out.println(openid + "： 该用户没有简历");//简历内容获取
//        }
        vo.setPost(post);
        vo.setResumeContent(resumeContent);

        //动态获取题库  2次循环
        Set<Integer> randomNumbers = getRandomNumbers();
        int a = 1;
        for (Integer randomNumber : randomNumbers) {
            QuestionBank questionBank = questionBankMapper.selectById(randomNumber);
            String topic = questionBank.getTopic();//题目
            String answer = questionBank.getAnswer();//答案
            String point = questionBank.getPoint();//点拨
            if (a == 1) {//两次循环分开放
                vo.setTopicA(topic);
                vo.setAnswerA(answer);
                vo.setPointA(point);
            } else {
                vo.setTopicB(topic);
                vo.setAnswerB(answer);
                vo.setPointB(point);
            }
            a = a + 1;
        }
        if (!Objects.equals(type,"1")){
            //处理通话次数
            WechatUserinfo userinfo = userinfoMapper.findByOpenid(openid);
            userinfo.setAiInterview(userinfo.getAiInterview()-1);
            userinfoMapper.updateById(userinfo);
        }


        return R.ok(vo, 200, "ok");
    }

    //获取简历内容(根据绝对地址拿到PDF文件转文本)
    public static String convertPdfToText(String pdfPath) throws IOException {
        File pdfFile = new File(pdfPath);

        // 验证文件存在且可读
        if (!pdfFile.exists()) {
            throw new IOException("PDF文件不存在: " + pdfPath);
        }
        if (!pdfFile.canRead()) {
            throw new IOException("无法读取PDF文件: " + pdfPath);
        }
        try (PDDocument document = PDDocument.load(pdfFile)) {
            // 检查加密
            if (document.isEncrypted()) {
                throw new IOException("加密PDF暂不支持: " + pdfPath);
            }
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(true); // 按页面布局排序
            return stripper.getText(document);
        }
    }

    public static void main(String[] args) {
        String pdfPath = "C:/Users/Administrator/Desktop/AI面试/905db149-dbea-45b7-a0d8-5a46f024e5a0.pdf"; // 替换为你的PDF路径
        try {
            String text = convertPdfToText(pdfPath);
            System.out.println("转换成功！文本内容：\n" + text);
        } catch (IOException e) {
            System.err.println("转换失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    //AI智能体通话记录回调
    private void generateSimplePdf(List<CallRecords> callRecords, String outputPath)
            throws DocumentException, java.io.IOException {
        File file = new File(outputPath);
        file.getParentFile().mkdirs();
        List<CallRecords> sortedRecords = callRecords.stream()
                .sorted(Comparator.comparing(CallRecords::getCreateTime))
                .collect(Collectors.toList());

        //使用A4页面尺寸，增加边距
        Document document = new Document(PageSize.A4, 40, 40, 60, 40);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        //添加背景处理器
        writer.setPageEvent(new BackgroundEvent(BACKGROUND_PATH));
        document.open();
        //添加标题（带底部间距）
        Paragraph title = new Paragraph("AI面试记录", titleFont);
        title.setAlignment(Element.ALIGN_CENTER);
        title.setSpacingAfter(25f);
        document.add(title);
        //标志变量
        boolean foundFirstQuestion = false;
        boolean isNewQuestion = false;
        String currentQuestion = "";
        boolean isFirstQuestion = false;
        //添加对话内容
        for (CallRecords record : sortedRecords) {
            String text = record.getText();
            text = text.replace("面试到此结束，感谢您的参与", "");
            //检查是否是新题目开始
            boolean isQuestionLine = text.contains("第") && text.contains("题") && "agent".equals(record.getRole());
            boolean isMSZJ = text.contains("面试总结") && "agent".equals(record.getRole());

            // 如果还未找到第一题
            if (!foundFirstQuestion) {
                if (isQuestionLine && text.contains("第一题")) {
                    foundFirstQuestion = true;
                    isFirstQuestion = true;
                    int startIndex = text.indexOf("第一题");
                    if (startIndex >= 0) {
                        text = text.substring(startIndex);
                    }
                } else {
                    continue;
                }
            }
            //处理题目行和面试总结行的换行符
            if (isQuestionLine) {
                text = text.replaceAll("(第\\s*[二三四五六七八九十]+\\s*题\\s*)", "\n\n$1");
                // 如果是新题目，增加额外间距
                if (!text.equals(currentQuestion)) {
                    currentQuestion = text;
                    isNewQuestion = true;
                    isFirstQuestion = text.contains("第一题");
                }
            } else if (isMSZJ) {
                text = text.replaceAll("(\\s*面试总结\\s*)", "\n\n$1");
                // 面试总结前增加额外间距
                isNewQuestion = true;
            }
            Font font = "agent".equals(record.getRole()) ? agentFont : userFont;
            String prefix = "agent".equals(record.getRole()) ? (isFirstQuestion ? "" : "面试官: ") : "用户: ";

            if (isNewQuestion) {
                isNewQuestion = false;
                isFirstQuestion = false;
            }

            Paragraph paragraph = new Paragraph(prefix + text, font);
            document.add(paragraph);
        }

        document.close();
    }

    // 修正背景图片铺满问题
    public static class BackgroundEvent extends PdfPageEventHelper {
        private final String backgroundImage;

        public BackgroundEvent(String backgroundImage) {
            this.backgroundImage = backgroundImage;
        }

        @Override
        public void onEndPage(PdfWriter writer, Document document) {
            try {
                PdfContentByte canvas = writer.getDirectContentUnder();
                Image img = Image.getInstance(backgroundImage);

                // 确保图片铺满整个页面 - 关键修改
                img.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight());
                img.setAbsolutePosition(0, 0);

                canvas.addImage(img);
            } catch (Exception e) {
                System.err.println("无法添加背景图片: " + e.getMessage());
            }
        }
    }

    //获取随机数方法 1-410中的 数字
    public static Set<Integer> getRandomNumbers() {
        Random random = new Random();
        Set<Integer> uniqueNumbers = new HashSet<>();  // 使用 HashSet 保证数字唯一性
        //循环直到集合中有 2 个不重复的数字 是否能够过滤某个值
        //添加判断 不让某个值添查询出来
        while (uniqueNumbers.size() < 2) {
            int randomNumber = random.nextInt(410) + 1;  // 生成 1 到 410 之间的随机数字 ,避免后续专业性问题
            uniqueNumbers.add(randomNumber);  // 自动忽略重复的数字
        }
        return uniqueNumbers;
    }
}
